using System;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Purchasing;
using PHSRAG.Utility;
using Constant = PHSRAG.Insight21.InsightUtilities.Constants;
using Helper=PHSRAG.WebControls.Helper;

namespace PHSRAG.Insight21
{
    /// <summary>
    /// The Financial Transaction Journal Entry page displays the details of the Journal 
    /// Entries accessible for the current user.
    /// This page can be navigated from Reconcile and Transaction Overview page.
    /// ------------------------------------------------------------------------
    /// 05/15/2008 - added sorting for journalEntryGrid - trackIt 7690
    /// ------------------------------------------------------------------------
    /// </summary>
    public partial class FinancialTransaction : NoCachePage
    {
        #region Constants(Private)

        private const string CurrentPageIndexKey = "CurrentPageIndex_534a7656-74ac-46b9-88c7-408eac9e1d46";
        ////private const string JournalIDKey				= "JournalIDKey_534a7656-74ac-46b9-88c7-408eac9e1d46";
        ////private const string StartDateKey				= "StartDateKey_534a7656-74ac-46b9-88c7-408eac9e1d46";
        ////private const string EndDateKey					= "EndDateKey_534a7656-74ac-46b9-88c7-408eac9e1d46";
        private const string ReferringPageKey = "ReferringPageKey_534a7656-74ac-46b9-88c7-408eac9e1d46";
        ////private const string FundNumberKey                 = "FundNumber_534a7656-74ac-46b9-88c7-408eac9e1d46";
        ////private const string AccountIDKey                  = "AccountID_534a7656-74ac-46b9-88c7-408eac9e1d46";

        #endregion

        #region Instance Variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        private ViewStateCachePolicy viewStateCachePolicy;

        #endregion

        #region Enum DataGridColumns

        /// <summary>
        /// The DataGridColumns enumeration defines values 
        /// for indexing columns
        /// </summary>
        private enum DataGridColumns
        {
            JournalID,
            Description,
            FundNumber,
            AccountNumber,
            AccountDescription,
            Amount,
            PostedBy
        }

        #endregion

        #region Private Properties

        /// <summary>
        /// Gets the Journal Id passed from the orginating page and cache it using pagecache policy
        /// </summary>
        private string JournalID
        {
            get
            {
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (incomingJournalData == null || incomingJournalData[Keys.JournalIDKey] == null) ? string.Empty :
                                                                                                                          (string) incomingJournalData[Keys.JournalIDKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[Keys.JournalIDKey] = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Gets the Start Date passed from the orginating page and cache it using pagecache policy
        /// </summary>
        private string StartDate
        {
            get
            {
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (incomingJournalData == null || incomingJournalData[Keys.JournalStartDateKey] == null) ? string.Empty :
                                                                                                                                 (string) incomingJournalData[Keys.JournalStartDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[Keys.JournalStartDateKey] = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Gets the End Date passed from the orginating page and cache it using pagecache policy
        /// </summary>
        private string EndDate
        {
            get
            {
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (incomingJournalData == null || incomingJournalData[Keys.JournalEndDateKey] == null) ? string.Empty :
                                                                                                                               (string) incomingJournalData[Keys.JournalEndDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[Keys.JournalEndDateKey] = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Gets the Journal Id passed from the orginating page and cache it using pagecache policy
        /// </summary>
        private string FundNumber
        {
            get
            {
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (incomingJournalData == null || incomingJournalData[Keys.FundNumberKey] == null) ? string.Empty :
                                                                                                                           (string) incomingJournalData[Keys.FundNumberKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[Keys.FundNumberKey] = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Gets the Journal Id passed from the orginating page and cache it using pagecache policy
        /// </summary>
        private string AccountNumber
        {
            get
            {
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (incomingJournalData == null || incomingJournalData[Keys.AccountNumberKey] == null) ? string.Empty :
                                                                                                                              (string) incomingJournalData[Keys.AccountNumberKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[Keys.AccountNumberKey] = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// This information is cached using the page cache policy
        /// Get: Return the value from the page cache policy, returns 0 if its not present in cache
        /// Set: Set the value and update the cache
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.JournalEntryPageKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                journalEntryGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.JournalEntryPageKey, h);
            }
        }

        /// <summary>
        /// Gets the JournalEntryDetails object.
        /// Call the static method GetCachedObject to get JournalEntryDetails object from  the cache. 
        /// Check if the object is null or incoming JournalId is not equal to cached JournalId, then instantiate  the 
        /// JournalEntryDetails object and cache it otherwise return  the cached object.
        /// </summary>
        private JournalEntryDetails JournalEntry
        {
            get
            {
                JournalEntryDetails journalEntryDetails =
                    ResultsCache.GetObject(cachePolicy, JournalEntryDetails.CacheKey) as JournalEntryDetails;
                if (journalEntryDetails == null || journalEntryDetails.JournalID != JournalID)
                {
                    journalEntryDetails = new JournalEntryDetails();
                    UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                    if (userContext == null)
                    {
                        throw new Exception("Unable to retrieve the UserContext from cache");
                    }
                    journalEntryDetails.Load(
                        DataAccess.GetConnectionString(),
                        userContext.DomainUserId,
                        JournalID, StartDate, EndDate
                        , FundNumber
                        , AccountNumber);

                    ResultsCache.SetObject(cachePolicy, JournalEntryDetails.CacheKey, journalEntryDetails);
                }
                return journalEntryDetails;
            }
        }

        /// <summary>
        /// Get and Set the referring page that brought us to the PODetails page. Using the value for the referring
        /// page, the navigation bars to be displayed on this page is decided.
        /// </summary>
        private string ReferringPage
        {
            get
            {
                object o = viewStateCachePolicy.GetCachedObject(ReferringPageKey);
                return (o == null) ? string.Empty : (string) o;
            }
            set { viewStateCachePolicy.Cache(ReferringPageKey, value); }
        }

        #endregion

        #region Event handlers

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Initialize the bread crumb control and load the data grid with the data.
        /// </summary>
        /// <param name="sender">Summary page which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            reportDownload.SQLReportName = "FinancialTransaction";

            annunciator.Title = annunciator.Message = string.Empty;

            string referringPage = (IsPostBack) ? ReferringPage : Path.GetFileName(Request.UrlReferrer.LocalPath);
            if (insightHeader.ModuleName == Constant.Modules.Agreements)
            {
                purchasingSubModuleNavigation.Visible = false;
                if (referringPage == Constant.ModulePages.TransactionOverview)
                {
                    agreementDetailsSubNavigation.Visible = false;
                    agreementsSubNavigation.Visible = true;
                    agreementsSubNavigation.EnableOverviewNavigation = true;
                }
                else if (referringPage == Constant.ModulePages.TransactionDetails)
                {
                    agreementsSubNavigation.EnableOverviewNavigation = false;
                    agreementsSubNavigation.Visible = true;
                    agreementDetailsSubNavigation.Visible = true;
                }

                ReferringPage = referringPage;
            }
            else
            {
                agreementDetailsSubNavigation.Visible = false;
                agreementsSubNavigation.Visible = false;
                ReferringPage = insightHeader.ModuleName;
            }

            if (!IsPostBack)
            {
                financialTransactionBC.Add("Journal Entry", Settings.GetKeyValue("Other.Purchasing.FinancialTransactionURL", ""),
                    (insightHeader.ModuleName == Constant.Modules.Agreements)
                        ? Settings.GetKeyValue("BreadCrumb.SubDetailPageLevel", Constants.DefaultSubDetailPageLevelValue)
                        : Settings.GetKeyValue("BreadCrumb.DetailPageLevel", Constants.DefaultDetailPageLevelValue));
                Hashtable incomingJournalData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

                string incomingJournalID = (incomingJournalData == null || incomingJournalData[Keys.JournalIDKey] == null) ? string.Empty :
                                                                                                                                              (string) incomingJournalData[Keys.JournalIDKey];
                JournalID = incomingJournalID;

                string incomingStartDate = (incomingJournalData == null || incomingJournalData[Keys.JournalStartDateKey] == null) ? string.Empty :
                                                                                                                                                     (string) incomingJournalData[Keys.JournalStartDateKey];
                StartDate = incomingStartDate;

                string incomingEndDate = (incomingJournalData == null || incomingJournalData[Keys.JournalEndDateKey] == null) ? string.Empty :
                                                                                                                                                 (string) incomingJournalData[Keys.JournalEndDateKey];
                EndDate = incomingEndDate;
                CurrentPageIndex = 0;

                //Uncache
                pageCachePolicy.UnCache(Keys.IncomingDataKey);

                LoadDataGrid();
            }
            if (CurrentPageIndex == 0)
            {
                InitializePager();
            }
            else
            {
                ManageNavigationLinks();
            }
            ManagePagination();
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            purchasingSubModuleNavigation.Reset();
            agreementDetailsSubNavigation.Reset();
            agreementsSubNavigation.Reset();
        }

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        /// <summary>
        /// Handles Send By Email button clicks by preparing a MailMessage to send back to the InsightDownloadBar control
        /// </summary>
        /// <remarks>
        /// This method generates the raw information needed for the InsightDownloadBar to process and send an e-mail
        /// with a link back to the page with the correct session settings.
        /// This page stores JournalID  into the database.
        ///  This page has no summary information, hence it passes an empty hashtable.
        /// </remarks>
        ///<param name="queryId">Last inserted value from the database</param>
        ///<param name="summaryInfo">Summary information to be send</param>
        ///<param name="webConfigURLKey">URL information to see the page</param>
        public void OnSendByEmail(out string webConfigURLKey, out int queryId, out Hashtable summaryInfo)
        {
            try
            {
                webConfigURLKey = "SubNavigation.PurchasingDetails.FinancialTransactionURL";
                string query = String.Format("{0}={1}",
                    Keys.JournalIDKey, JournalID
                    );
                queryId = JournalEntryDetails.GetQueryId(query);
                //There is no summary information this page
                summaryInfo = null;
            }
            catch (Exception e)
            {
                webConfigURLKey = null;
                queryId = -1;
                summaryInfo = null;
                ExceptionReport.WriteToEventLog("Send By Email click handler", e, true, ExceptionReport.ReportType.Error);
            }
        }

        /// <summary>
        /// Handler for event raised when each data grid item is bound to a datacolumn.
        /// Check for negative values for the Amount field and apply appropriate style if negative.
        /// Formatting is applied to Item types and Alternating Item types.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    TableCell journalAmount = e.Item.Cells[(int) DataGridColumns.Amount];
                    decimal amount = Convert.ToDecimal(journalAmount.Text);
                    //amount = Decimal.Negate(amount);
                    if (amount < 0)
                    {
                        journalAmount.CssClass = Constants.DeficitStyle;
                    }
                    journalAmount.Text = Helper.ProcessDecimals(amount);
                }
                    // Load the screen totals bar.
                else if (e.Item.ItemType == ListItemType.Footer)
                {
                    e.Item.Cells[0].Text = "Total";

                    if (JournalEntry.TotalAmount < 0)
                    {
                        e.Item.Cells[5].CssClass = "DataGridFooterRed";
                    }
                    e.Item.Cells[5].Text = Helper.ProcessDecimals(JournalEntry.TotalAmount);
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} Amount fields are not in correct format.", ExceptionReport.GetExceptionInfo(ex, false));
            }
        }

        #endregion

        #region Paging event handlers

        /// <summary>
        /// Handler for the event raised when the FirstPage link is clicked in the Pager control.
        /// Set the current page index to 0, bind the datagrid with data and manage navigation links.
        /// To avoid superfluous data binding activites, no action is taken if the current page index is already 0.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = 0;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the LastPage link is clicked in the Pager control.
        /// Set the current page index to one less than the total page count (index is 0-based), bind the datagrid with
        /// data and manage navigation links.
        /// To avoid superfluous data binding activites, no action is taken if the current 
        /// page index is already corresponding to the last page.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = pagerAboveDatagrid.PageCount - 1;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the NextPage link is clicked in the Pager control.
        /// Increment the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            ++CurrentPageIndex;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the PreviousPage link is clicked in the Pager control.
        /// Decrement the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            --CurrentPageIndex;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        #endregion

        #region Private Methods

        /// Load the datagrid with the data retrieved from the Business Object.
        /// If there is an exception, display the error message via the annunciator.
        private void LoadDataGrid()
        {
            try
            {
                JournalEntryDetails journalEntryDetails = JournalEntry;

                journalEntryGrid.VirtualItemCount = pagerAboveDatagrid.RecordCount
                    = pagerBelowDatagrid.RecordCount = journalEntryDetails.Count;

                int currentPageIndex = CurrentPageIndex;
                int pageCount = (pagerAboveDatagrid.RecordCount/journalEntryGrid.PageSize) +
                    (((pagerAboveDatagrid.RecordCount%journalEntryGrid.PageSize) == 0) ? 0 : 1);
                pagerBelowDatagrid.PageCount = pagerAboveDatagrid.PageCount = pageCount;
                pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = currentPageIndex + 1;

                journalEntryGrid.DataSource = journalEntryDetails.GetJournalEntryList
                    (currentPageIndex*journalEntryGrid.PageSize, journalEntryGrid.PageSize);
                journalEntryGrid.DataBind();

                if (journalEntryGrid.Items.Count == 0)
                {
                    journalEntryGrid.Visible = pagerBelowDatagrid.Visible =
                        pagerAboveDatagrid.Visible = false;
                    annunciator.Message = "No Journal Entry data found for user";
                }
                else
                {
                    journalEntryGrid.Visible = true;
                }


                asOfDate.Text = DateTime.Today.ToShortDateString();
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} Error occurred while loading the data.", ExceptionReport.GetExceptionInfo(ex, false));
            }
        }

        /// <summary>
        /// Initialize the first record, last record and current page values for the pager controls
        /// This will be called only when a pager needs to be intialized, 
        /// so set the first record and the current page values to 1 and the last page value to the grid page size 
        /// Set the current page index to 0 and manage the navigation links.
        /// </summary>
        private void InitializePager()
        {
            pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = 1;
            pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = 1;
            CurrentPageIndex = 0;
            ManageNavigationLinks();
        }

        /// <summary>
        /// ManageNavigationLinks determines which links should be active and which should be inactive
        /// for the first page and last page links.
        /// </summary>
        private void ManageNavigationLinks()
        {
            pagerBelowDatagrid.EnableFirstPage = pagerAboveDatagrid.EnableFirstPage =
                pagerBelowDatagrid.EnablePreviousPage = pagerAboveDatagrid.EnablePreviousPage =
                    (CurrentPageIndex != 0);

            pagerBelowDatagrid.EnableLastPage = pagerAboveDatagrid.EnableLastPage =
                pagerBelowDatagrid.EnableNextPage = pagerAboveDatagrid.EnableNextPage =
                    (CurrentPageIndex != (pagerAboveDatagrid.PageCount - 1));
        }

        /// <summary>
        /// Manages the pagination logic.
        /// Set the First record and last record values for the pager controls
        /// based on the current page index and the data grid page size respectively
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            journalEntryGrid.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*journalEntryGrid.PageSize;

            pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = startIndex + 1;
            pagerBelowDatagrid.LastRecord = pagerAboveDatagrid.LastRecord =
                Math.Min(startIndex + journalEntryGrid.PageSize, JournalEntry.Count);
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            viewStateCachePolicy = new PHSRAG.Insight21.Policy.ViewStateCachePolicy(this.ViewState);

            pagerAboveDatagrid.FirstPage += new CommandEventHandler(this.OnFirstPage);
            pagerAboveDatagrid.LastPage += new CommandEventHandler(this.OnLastPage);
            pagerAboveDatagrid.NextPage += new CommandEventHandler(this.OnNextPage);
            pagerAboveDatagrid.PreviousPage += new CommandEventHandler(this.OnPreviousPage);

            pagerBelowDatagrid.FirstPage += new CommandEventHandler(this.OnFirstPage);
            pagerBelowDatagrid.LastPage += new CommandEventHandler(this.OnLastPage);
            pagerBelowDatagrid.NextPage += new CommandEventHandler(this.OnNextPage);
            pagerBelowDatagrid.PreviousPage += new CommandEventHandler(this.OnPreviousPage);

            this.reportDownload.FailedAction += new CommandEventHandler(OnDownloadFailed);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.insightHeader.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnHeaderNavigate);
            this.reportDownload.SendByEmail += new PHSRAG.WebControls.DownloadBar.EmailEventHandler(this.OnSendByEmail);
            this.journalEntryGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            this.journalEntryGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.journalEntryGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region DataGrid events

        private void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    JournalEntryDetails journalEntry = JournalEntry;

                    Label sortSymbol = new Label();
                    sortSymbol.CssClass = "Sort";
                    sortSymbol.Text = journalEntry.SortAscending ? Constants.SortAscendingText : Constants.SortDescendingText;
                    sortSymbol.Font.Name = Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in journalEntryGrid.Columns)
                    {
                        columnMap[column.SortExpression] = journalEntryGrid.Columns.IndexOf(column);
                    }

                    string sortColumn = journalEntry.SortColumn;

                    if (columnMap.ContainsKey(sortColumn))
                    {
                        (e.Item.Cells[(int) columnMap[sortColumn]]).Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion

        #region Sort

        private void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    JournalEntry.Sort(e.SortExpression);
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception excp)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(excp, false);
            }
        }

        #endregion
    }
}